package output;

import java.io.*;
import java.util.*;

public class SerialObjectFileIterator implements Iterable<Serializable> {

	private ObjectInputStream in;
	private String filename;
	private Serializable curr;
	private Serializable next;
	private boolean eofReached;
	
	public String getFilename() {
		return filename;
	}
	
	public SerialObjectFileIterator(String filename) {
		try {
			in = new ObjectInputStream(new FileInputStream(filename));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		eofReached = false;
	}
	
	public boolean reset() {
		try {
			in.reset();
			return true;
		} catch (IOException e) {
		}
		return false;
	}
	
	private Serializable read() {
		try {
			curr = next;
			next = (Serializable) in.readObject();
		} catch (EOFException ex) {
			eofReached = true;
		} catch (IOException ex) {
			next = null;
		} catch (ClassNotFoundException ex) {
			ex.printStackTrace();
		}
		return curr;
	}
	
	@Override
	public Iterator<Serializable> iterator() {
		return new Iterator<Serializable>() {
			
			@Override
			public void remove() {
				throw new UnsupportedOperationException();
			}
			
			@Override
			public Serializable next() {
				return read();
			}
			
			@Override
			public boolean hasNext() {
				return !eofReached;
			}
		};
	}

}
